import React, { useState, useEffect } from 'react';
import { Card, Button, Tag, message } from 'antd';
import { BulbOutlined } from '@ant-design/icons';
import { Customer } from '../types';
import { getMarketingScenarios, MarketingScenario } from '../data/marketingScenarios';
import { streamApiService } from '../lib/streamApi';

// const { Text } = Typography; // 暂时未使用

interface MarketingScenariosProps {
  currentCustomer: Customer;
  onSendToChat?: (content: string) => void; // 添加发送到聊天框的回调
  deepThinkingEnabled?: boolean;
  thinkingCallbacks?: any; // 思考过程回调
}

interface ScenarioState {
  [scenarioId: string]: {
    isGenerating: boolean;
    generatedContent: string | null;
    isRecommended: boolean; // 是否为推荐场景
  };
}

const MarketingScenarios: React.FC<MarketingScenariosProps> = ({ currentCustomer, onSendToChat, deepThinkingEnabled = true, thinkingCallbacks }) => {
  const [scenarioStates, setScenarioStates] = useState<ScenarioState>({});

  // 根据客户画像匹配推荐场景
  const getRecommendedScenarios = (customer: Customer): string[] => {
    const recommendedIds: string[] = [];

    // 根据风险等级推荐
    if (customer.risk_preference === 'R1' || customer.risk_preference === 'R2') {
      recommendedIds.push('conservative_retirement', 'stable_income', 'wealth_preservation');
    } else if (customer.risk_preference === 'R3') {
      recommendedIds.push('balanced_growth', 'education_funding', 'home_purchase');
    } else {
      recommendedIds.push('aggressive_growth', 'entrepreneurship', 'global_investment');
    }

    // 根据资产规模推荐
    const totalAssets = customer.total_investment / 10000; // 转换为万元
    if (totalAssets >= 500) {
      recommendedIds.push('high_net_worth', 'tax_optimization', 'estate_planning');
    } else if (totalAssets >= 100) {
      recommendedIds.push('middle_class_planning', 'insurance_planning', 'retirement_prep');
    } else {
      recommendedIds.push('starter_investment', 'emergency_fund', 'basic_protection');
    }

    return recommendedIds;
  };

  // 初始化场景状态和自动生成推荐场景话术
  useEffect(() => {
    const allScenarios = getMarketingScenarios();
    const recommendedIds = getRecommendedScenarios(currentCustomer);

    const initialStates: ScenarioState = {};

    // 初始化所有场景状态
    allScenarios.forEach(scenario => {
      const isRecommended = recommendedIds.includes(scenario.id);
      initialStates[scenario.id] = {
        isGenerating: false, // 所有场景都不自动生成，等待用户手动点击
        generatedContent: null,
        isRecommended
      };
    });

    setScenarioStates(initialStates);

    // 不再自动生成推荐场景，改为用户手动点击生成

  }, [currentCustomer]);

  // 手动生成营销话术
  const generateMarketingContent = async (scenario: MarketingScenario) => {
    setScenarioStates(prev => ({
      ...prev,
      [scenario.id]: {
        ...prev[scenario.id],
        isGenerating: true,
        generatedContent: null
      }
    }));

    try {
      // 构建完整的提示词
      const fullPrompt = scenario.prompt || `生成${scenario.title}的营销话术`;

      // 使用流式API生成内容
      await streamApiService.sendMessageStream(
        fullPrompt,
        // onChunk: 处理流式数据块
        (_chunk: string, accumulated: string, phase?: 'reasoning' | 'llm') => {
          // 只在LLM阶段（或没有phase信息时）更新UI显示流式内容
          if (phase === 'llm' || !phase) {
            setScenarioStates(prev => ({
              ...prev,
              [scenario.id]: {
                ...prev[scenario.id],
                isGenerating: true,
                generatedContent: accumulated
              }
            }));
          }
        },
        // onComplete: 完成回调
        (fullMessage) => {
          setScenarioStates(prev => ({
            ...prev,
            [scenario.id]: {
              ...prev[scenario.id],
              isGenerating: false,
              generatedContent: fullMessage.text
            }
          }));
          message.success('营销话术生成完成');
        },
        // onError: 错误回调
        (error) => {
          console.error('营销话术生成失败:', error);
          setScenarioStates(prev => ({
            ...prev,
            [scenario.id]: {
              ...prev[scenario.id],
              isGenerating: false,
              generatedContent: null
            }
          }));
          message.error('生成失败，请重试');
        },
        currentCustomer.name || '客户',
        currentCustomer?.session_id,
        [],
        'market_agent',
        scenario.title,
        !deepThinkingEnabled, // enableThinking - 反转逻辑：false时enableThinking=true
        thinkingCallbacks // 传递思考过程回调
      );

    } catch (error) {
      console.error('营销话术生成异常:', error);
      setScenarioStates(prev => ({
        ...prev,
        [scenario.id]: {
          ...prev[scenario.id],
          isGenerating: false,
          generatedContent: null
        }
      }));
      message.error('生成失败，请重试');
    }
  };

  // 复制话术
  const handleCopyContent = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      message.success('营销话术已复制到剪贴板');
    } catch (error) {
      // 降级方案
      const textArea = document.createElement('textarea');
      textArea.value = content;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      message.success('营销话术已复制到剪贴板');
    }
  };

  // 发送话术
  const handleSendContent = (content: string) => {
    if (onSendToChat) {
      onSendToChat(content);
      message.success('营销话术已发送至聊天框');
    } else {
      message.error('发送功能暂不可用');
    }
  };

  const allScenarios = getMarketingScenarios();

  return (
    <div className="space-y-4 px-4">
      {/* 添加CSS动画样式 */}
      <style>
        {`
          @keyframes pulse-glow {
            0%, 100% {
              opacity: 1;
              transform: scale(1);
            }
            50% {
              opacity: 0.7;
              transform: scale(1.1);
            }
          }
          
          .pulse-animation {
            animation: pulse-glow 2s ease-in-out infinite;
          }
        `}
      </style>

      {/* 按推荐状态排序：推荐场景在前，其他场景在后 */}
      {allScenarios
        .sort((a, b) => {
          const aIsRecommended = scenarioStates[a.id]?.isRecommended || false;
          const bIsRecommended = scenarioStates[b.id]?.isRecommended || false;

          // 推荐场景排在前面
          if (aIsRecommended && !bIsRecommended) return -1;
          if (!aIsRecommended && bIsRecommended) return 1;

          // 如果都是推荐或都不是推荐，保持原有顺序
          return 0;
        })
        .map((scenario) => {
          const scenarioState = scenarioStates[scenario.id];
          const isGenerating = scenarioState?.isGenerating || false;
          const generatedContent = scenarioState?.generatedContent;
          const isRecommended = scenarioState?.isRecommended || false;

          return (
            <Card
              key={scenario.id}
              className={`marketing-scenario-card ${isRecommended ? 'recommended' : 'normal'
                }`}
            >
              {/* 场景标题和标签 */}
              <div className="flex items-start gap-3 marketing-scenario-header">
                <div className="flex-shrink-0 mt-1">
                  <BulbOutlined
                    className={`text-lg ${isRecommended
                        ? 'text-blue-700 pulse-animation'
                        : 'text-blue-500'
                      }`}
                  />
                </div>
                <div className="flex-1">
                  <div className="flex items-center justify-between mb-2">
                    <div className="marketing-scenario-title">{scenario.title}</div>
                    {isRecommended && (
                      <Tag className="marketing-recommended-tag">
                        智能推荐
                      </Tag>
                    )}
                  </div>
                  <div className="marketing-scenario-description">
                    {scenario.description}
                  </div>

                  {/* 显示适用客户类型 */}
                  <div className="marketing-customer-tags">
                    {scenario.targetCustomers.slice(0, 3).map((target, index) => (
                      <Tag key={index} color="geekblue">
                        {target}
                      </Tag>
                    ))}
                    {scenario.targetCustomers.length > 3 && (
                      <Tag color="default">
                        +{scenario.targetCustomers.length - 3}
                      </Tag>
                    )}
                  </div>
                </div>
              </div>

              {/* 生成的话术内容 */}
              {generatedContent && (
                <div className="marketing-generated-content">
                  <div className="flex items-center gap-2 marketing-content-header">
                    <div className="marketing-content-indicator"></div>
                    <div className="marketing-content-label">
                      {isRecommended ? '智能推荐话术' : '生成的营销话术'}
                    </div>
                  </div>
                  <div className="marketing-content-text">
                    {generatedContent}
                  </div>
                </div>
              )}

              {/* 加载状态显示 */}
              {isGenerating && (
                <div className="marketing-loading-state">
                  <div className="flex items-center gap-2">
                    <div className="marketing-loading-indicator"></div>
                    <div className="marketing-loading-text">
                      {isRecommended ? 'AI正在为您智能生成推荐话术...' : '正在生成营销话术...'}
                    </div>
                  </div>
                </div>
              )}

              {/* 操作按钮 */}
              <div className="flex marketing-actions">
                {!generatedContent && !isGenerating ? (
                  <Button
                    type="primary"
                    onClick={() => generateMarketingContent(scenario)}
                    className={`${isRecommended
                        ? 'bg-blue-700 hover:bg-blue-800 border-blue-700'
                        : 'bg-blue-500 hover:bg-blue-600'
                      }`}
                  >
                    生成营销话术
                  </Button>
                ) : generatedContent ? (
                  <>
                    <Button
                      onClick={() => handleCopyContent(generatedContent)}
                    >
                      复制
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => handleSendContent(generatedContent)}
                      className="bg-green-500 hover:bg-green-600"
                    >
                      发送至聊天框
                    </Button>
                    <Button
                      onClick={() => setScenarioStates(prev => ({
                        ...prev,
                        [scenario.id]: {
                          ...prev[scenario.id],
                          isGenerating: false,
                          generatedContent: null
                        }
                      }))}
                    >
                      重新生成
                    </Button>
                  </>
                ) : null}
              </div>

              {/* 场景统计信息 */}
              <div className="marketing-stats">
                <div className="flex justify-between">
                  <span className="marketing-stats-item marketing-data-usage">使用次数: {scenario.useCount}</span>
                  <span className="marketing-stats-item marketing-data-success">成功率: {scenario.successRate}%</span>
                  <span className={`marketing-stats-item marketing-data-priority ${scenario.priority === 'high' ? 'high' : ''}`}>
                    优先级: {scenario.priority === 'high' ? '高' : scenario.priority === 'medium' ? '中' : '低'}
                  </span>
                </div>
              </div>
            </Card>
          );
        })}
    </div>
  );
};

export default MarketingScenarios; 